﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using log4net;
using System.Diagnostics;

namespace SkypeTranslater
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application
	{
		internal static SKYPE4COMLib.Skype Skype = null;
		internal static log4net.ILog Log;
		internal GroupCollection m_collection = null;
		bool m_otherInstanceRun = false;
		internal static bool TranslateOutlook = false;
		internal static bool NeedRunSkype = false;
		internal static bool IsSkypeRunning = false;

		public App()
			: base()
		{
			Log = log4net.LogManager.GetLogger(typeof(App).FullName);
			log4net.Config.XmlConfigurator.Configure();

			this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
		}

		void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
		{
			Log.Fatal(e.Exception.Message, e.Exception);
			e.Handled = false;
		}

		protected override void OnStartup(StartupEventArgs e)
		{
			base.OnStartup(e);

			if (IsAppAlreadyRunning())
			{
				m_otherInstanceRun = true;
				return;
			}

			Log.Info("Application start running");
			Skype = new SKYPE4COMLib.Skype();

			if (string.Compare(System.Configuration.ConfigurationManager.AppSettings["IsCloseAppOnSkypeClosed"], "true", true) == 0)
			{
				if (!Skype.Client.IsRunning)
				{
					MessageBox.Show("Skype client isn't runing!!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
					App.Current.Shutdown();
					return;
				}
			}

			Log.Info("Checking for Skype running");

			IsSkypeRunning = Skype.Client.IsRunning;
			if (!Skype.Client.IsRunning && NeedRunSkype)
			{
				Log.Info("Skype not ran. Try to run Skype instance");
				Skype.Client.Start(true, true);
			}

			Log.Info("Load group collection");
			m_collection = new GroupCollection();
			string filePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Groups.xml");
			RecoveryModule.RecoveryGroupsXml(filePath);
			m_collection.LoadFromXml(filePath);

			var outlookCol = new Outlook.OutlookItemCollection();
			outlookCol.Load(filePath);

			TranslateOutlook = string.Compare("true", System.Configuration.ConfigurationManager.AppSettings["TranslateOutlook"], true) == 0;
			NeedRunSkype = string.Compare("true", System.Configuration.ConfigurationManager.AppSettings["NeedRunSkype"], true) == 0;

			SkypeTranslater.MainWindow wind = new MainWindow();
			wind.Show();
			
			wind.SetColection(m_collection);
			wind.SetColectionOutlook(outlookCol);

			this.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
			this.MainWindow = wind;
		}


		private static bool IsAppAlreadyRunning()
		{
			bool result = false;
			Process currentProcess = Process.GetCurrentProcess();

			if (Process.GetProcessesByName(currentProcess.ProcessName).Any(p => p.Id != currentProcess.Id))
			{
				result = true;
				try
				{
					IntPtr hWnd = FindWindow(null, "Skype message translater");
					if (hWnd != IntPtr.Zero)
					{
						SetForegroundWindow(hWnd);
					}
				}
				catch (Exception ex) { Log.Error("WinApi", ex); }

				Current.Shutdown();
				return result;
			}
			return result;
		}

		protected override void OnExit(ExitEventArgs e)
		{
			base.OnExit(e);

			Log.Info("Application begin exit");
			log4net.LogManager.Shutdown();

			if (m_otherInstanceRun)
				return;

			m_collection.SaveToXml(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Groups.xml"));

			if (Skype != null)
			{
			}
		}

		[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
		private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

		[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
		[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
		private static extern bool SetForegroundWindow(IntPtr hWnd);
	}
}
